/*******************************************************************************
 * Copyright (c) 2008 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *     Bartosz Michalik (bartosz.michalik@gmail.com)
 *******************************************************************************/
package org.eclipse.pde.internal.ui.editor.product;

import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.*;
import org.eclipse.pde.core.IModelChangedEvent;
import org.eclipse.pde.core.IModelChangedListener;
import org.eclipse.pde.core.plugin.*;
import org.eclipse.pde.internal.core.*;
import org.eclipse.pde.internal.core.iproduct.*;
import org.eclipse.pde.internal.core.product.ChangeNameTransform;
import org.eclipse.pde.internal.core.product.ProductTransformFactory;
import org.eclipse.pde.internal.ui.editor.PDEFormPage;
import org.eclipse.pde.internal.ui.editor.TreeSection;
import org.eclipse.pde.internal.ui.editor.plugin.ExtensionContentProvider;
import org.eclipse.pde.internal.ui.editor.plugin.ExtensionsSection;
import org.eclipse.pde.internal.ui.editor.product.customization.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;

/**
 * First customization section - merely asks if you wish to use customizations.
 */
public class ExtensionCustomizationSection extends TreeSection {

	private class NameEditingSupport extends EditingSupport {

		private CellEditor fEditor;
		private String fOldValue;

		public NameEditingSupport(TreeViewer viewer) {
			super(viewer);
			fEditor = new TextCellEditor(viewer.getTree());
			fOldValue = ""; //$NON-NLS-1$

		}

		protected boolean canEdit(Object object) {
			if (object instanceof IPluginElement) {
				IPluginElement element = (IPluginElement) object;
				IPluginAttribute attribute = element.getAttribute(IPluginObject.P_NAME);
				if (attribute != null) {
					String name = attribute.getValue();
					return name != null && !name.equals(""); //$NON-NLS-1$
				}
			}
			return false;
		}

		protected CellEditor getCellEditor(Object element) {
			return fEditor;
		}

		protected Object getValue(Object object) {
			IPluginElement element = (IPluginElement) object;
			IProductTransform transform = getCustomizationInfo().getTransformsManager().getTransformFor(element);
			String name;
			if (transform instanceof ChangeNameTransform) {
				name = ((ChangeNameTransform) transform).getName();
			} else {
				name = element.getAttribute(IPluginObject.P_NAME).getValue();
				name = ExtensionsSection.stripShortcuts(name);
				name = element.getResourceString(name);
			}
			fOldValue = name;
			return name;
		}

		protected void setValue(Object object, Object value) {
			if (fOldValue.equals(value))
				return;
			IPluginElement element = (IPluginElement) object;
			ChangeNameTransform transform = new ChangeNameTransform(getCustomizationInfo().getModel());
			transform.setTransformedObject(element);
			transform.setName((String) value);
			getCustomizationInfo().addTransform(transform);
		}

	}

	private class NameEditorActivationStrategy extends ColumnViewerEditorActivationStrategy {

		public NameEditorActivationStrategy(ColumnViewer viewer) {
			super(viewer);
		}

		protected boolean isEditorActivationEvent(ColumnViewerEditorActivationEvent event) {
			boolean singleSelect = ((IStructuredSelection) getViewerSelection()).size() == 1;
			return singleSelect && event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
		}
	}

	private class RefreshListener implements IModelChangedListener, IExtensionDeltaListener, IPluginModelListener {

		private TreeViewer fViewer;

		public RefreshListener(TreeViewer viewer) {
			this.fViewer = viewer;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.pde.core.IModelChangedListener#modelChanged(org.eclipse.pde.core.IModelChangedEvent)
		 */
		public void modelChanged(IModelChangedEvent event) {
			if (IModelChangedEvent.WORLD_CHANGED == event.getChangeType()) {
				refresh();
				return;
			}
			Object[] changedObjects = event.getChangedObjects();
			boolean needsUpdating = false;
			for (int i = 0; i < changedObjects.length; ++i) {
				if (changedObjects[i] instanceof IProductTransform) {
					refreshObject((IProductTransform) changedObjects[i]);
				} else {
					needsUpdating = true;
					break;
				}
			}
			if (needsUpdating)
				refresh();
		}

		private void refreshObject(IProductTransform object) {
			IPluginObject transformed = (IPluginObject) object.getTransformedObject();
			List toUpdate = new LinkedList();
			while (transformed != null) {
				toUpdate.add(transformed);
				transformed = transformed.getParent();
			}
			transformed = (IPluginObject) object.getTransformedObject();
			fViewer.update(toUpdate.toArray(), null);
			fViewer.refresh(transformed, true);
			fViewer.setSelection(new StructuredSelection(transformed), true);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.pde.internal.core.IExtensionDeltaListener#extensionsChanged(org.eclipse.pde.internal.core.IExtensionDeltaEvent)
		 */
		public void extensionsChanged(IExtensionDeltaEvent event) {
			refresh();
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.pde.internal.core.IPluginModelListener#modelsChanged(org.eclipse.pde.internal.core.PluginModelDelta)
		 */
		public void modelsChanged(PluginModelDelta delta) {
			Display.getDefault().asyncExec(new Runnable() {

				public void run() {
					refresh();
				}

			});
		}

		/**
		 * TODO optimize
		 */
		private void refresh() {
			IProductModel productModel = getProductModel();
			if (productModel == null)
				return;
			fViewer.setInput(productModel.getProduct());
			fViewer.refresh();
		}

	}

	private RefreshListener fRefreshListener;
	private ExtensionCustomizationLabelProvider fLabelProvider;
	private TreeViewer fTreeViewer;

	//buttons actions

	private TransformationAction[] fButtonActions;

	protected void selectionChanged(IStructuredSelection selection) {
		enableButtons();
	}

	/**
	 * @param page
	 * @param parent
	 * @param style
	 */
	public ExtensionCustomizationSection(PDEFormPage page, Composite parent) {
		super(page, parent, Section.DESCRIPTION, new String[] {"Restore To Configuration", "Remove From Configuration"});
		fButtonActions = new TransformationAction[2];
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.pde.internal.ui.editor.PDESection#createClient(org.eclipse.ui.forms.widgets.Section,
	 *      org.eclipse.ui.forms.widgets.FormToolkit)
	 */
	protected void createClient(Section section, FormToolkit toolkit) {
		section.setText("Extensions");
		GridData sectionData = new GridData(SWT.FILL, SWT.FILL, true, true);
		sectionData.horizontalSpan = 2;
		section.setLayoutData(sectionData);
		final Composite container = createClientContainer(section, 3, toolkit);
		createViewerPartControl(container, SWT.MULTI, 3, toolkit);
		fTreeViewer = getTreePart().getTreeViewer();
		fLabelProvider = new ExtensionCustomizationLabelProvider(getCustomizationInfo(), toolkit);
		fTreeViewer.setContentProvider(new ExtensionContentProvider());
		fTreeViewer.setLabelProvider(fLabelProvider);
		//make column editor work
		ViewerColumn column = null;
		try {
			//TODO remove after is public in Eclipse [CRITICAL]
			Method method = ColumnViewer.class.getDeclaredMethod("getViewerColumn", new Class[] {int.class});
			method.setAccessible(true);
			column = (ViewerColumn) method.invoke(fTreeViewer, new Object[] {new Integer(0)});
		} catch (Exception e) {
			//cannot happened where there is no security manager
			e.printStackTrace();
		}

		TreeViewerEditor.create(fTreeViewer, new NameEditorActivationStrategy(fTreeViewer), ColumnViewerEditor.DEFAULT);
		column.setEditingSupport(new NameEditingSupport(fTreeViewer));
		fTreeViewer.setComparer(new IElementComparer() {

			public boolean equals(Object a, Object b) {
				if (a.equals(b))
					return true;
				if (!a.getClass().equals(b.getClass()))
					return false;
				if (a instanceof IPluginObject && b instanceof IPluginObject) {
					String xp1 = ProductTransformFactory.toXPath(a, true);
					String xp2 = ProductTransformFactory.toXPath(b, true);
					return xp1.equals(xp2);
				}
				return false;
			}

			public int hashCode(Object element) {
				return element.hashCode();
			}

		});

		getTreePart().setEnabled(getCustomizationInfo().getUseCustomizations());
		getProductModel().addModelChangedListener(new IModelChangedListener() {

			public void modelChanged(IModelChangedEvent event) {
				if (ICustomizationInfo.P_USE.equals(event.getChangedProperty())) {
					Boolean b = (Boolean) event.getNewValue();
					getTreePart().setEnabled(b.booleanValue());
				}

			}

		});

		toolkit.paintBordersFor(container);
		section.setClient(container);
		fRefreshListener = new RefreshListener(fTreeViewer);
		fTreeViewer.setInput((getProductModel()).getProduct());
		PDECore.getDefault().getModelManager().addExtensionDeltaListener(fRefreshListener);
		PDECore.getDefault().getModelManager().addPluginModelListener(fRefreshListener);
		getProductModel().addModelChangedListener(fRefreshListener);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.forms.AbstractFormPart#dispose()
	 */
	public void dispose() {
		getProductModel().removeModelChangedListener(fRefreshListener);
		PDECore.getDefault().getModelManager().removeExtensionDeltaListener(fRefreshListener);
		PDECore.getDefault().getModelManager().removePluginModelListener(fRefreshListener);
		super.dispose();
	}

	/**
	 * The customization info for this product.
	 * 
	 * @return the info
	 */
	protected ICustomizationInfo getCustomizationInfo() {
		ICustomizationInfo customizationInfo = (getProductModel()).getProduct().getCustomizationInfo();
		if (customizationInfo == null) {
			IProductModel productModel = getProductModel();
			customizationInfo = productModel.getFactory().createCustomizationInfo();
			productModel.getProduct().setCustomizationInfo(customizationInfo);
		}
		return customizationInfo;
	}

	/**
	 * Add actions that do the magic 
	 */
	protected void fillContextMenu(IMenuManager manager) {
		IStructuredSelection selection = (IStructuredSelection) fTreeViewer.getSelection();
		if (!selection.isEmpty()) {
			TransformationAction[] actions = new TransformationAction[3];
			actions[0] = new RemoveFeatureAction(getCustomizationInfo(), selection);
			actions[1] = new ChangeNameAction(getCustomizationInfo(), selection, fTreeViewer);
			actions[2] = new RestoreTransformAction(getCustomizationInfo(), selection);
			for (int i = 0; i < actions.length; ++i) {
				if (actions[i].isEnabled())
					manager.add(actions[i]);
			}
		}
	}

	/**
	 * @return model
	 */
	private IProductModel getProductModel() {
		return (IProductModel) getPage().getPDEEditor().getAggregateModel();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.pde.internal.ui.editor.StructuredViewerSection#buttonSelected(int)
	 */
	protected void buttonSelected(int index) {
		fButtonActions[index].run();
	}

	protected void enableButtons() {
		if (fTreeViewer == null)
			return;
		IStructuredSelection selection = (IStructuredSelection) fTreeViewer.getSelection();
		fButtonActions[0] = new RestoreTransformAction(getCustomizationInfo(), selection);
		fButtonActions[1] = new RemoveFeatureAction(getCustomizationInfo(), selection);
		for (int i = 0; i < fButtonActions.length; ++i) {
			getStructuredViewerPart().getButton(i).setEnabled(fButtonActions[i].isEnabled());
		}

	}
}
